<template>

    <el-card shadow="never" class="border-0" v-loading.fullscreen.lock="fullscreenLoading">
        <!-- 搜索 -->
        <SearchForm :model="searchForm" @search="getList" @reset="resetSearchForm">
            <SearchItem label="">
                <div class="mt-4" style="width: 100%;margin-left: 0px !important;">
                    <el-input v-model="searchForm.name" placeholder="用户名" class="input-with-select">
                        <template #prepend>
                            <el-button :icon="Search" />
                        </template>
                        <template #append>
                            <el-select v-model="searchForm.type" placeholder="请选择用户类型">
                                <el-option key="0" label="全部" value="" />
                                <el-option key="0" label="个人用户" value="0" />
                                <el-option key="1" label="企业用户" value="1" />
                            </el-select>
                        </template>
                    </el-input>
                </div>
            </SearchItem>
        </SearchForm>

        <!-- 新增|刷新 -->
        <ListHeader layout="create,refresh" @create="handleCreate" @refresh="getList" />

        <el-table :data="tableData" stripe style="width: 100%; text-align: center" v-loading="loading" border>
            <el-table-column type="index" label="序号" width="100" style="text-align: center" align="center " />
            <el-table-column label="类型" width="200">
                <template #default="scope">
                    <el-tag type="primary" v-if="scope.row.type == 0">个人用户</el-tag>
                    <el-tag type="info" v-else>企业用户</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="用户" width="200">
                <template #default="scope">
                    <el-tag type="primary" v-if="scope.row.type == 0">{{ scope.row.username }}</el-tag>
                    <el-tag type="info" v-else>{{ scope.row.company_name }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="en_name" label="app平台" width="100" style="text-align: center" align="center " />
            <el-table-column label="app账户目录位置" >
                <template #default="scope">

                    <el-tag type="primary" v-if="scope.row.app_account_upload">{{ scope.row.app_account_upload
                        }}</el-tag>
                    <el-tag type="info" v-else>
                        <el-button @click="login_app(scope.row)" text type="primary" class="p-1">
                            <el-icon class="el-icon--left" :size="16">
                                <Key />
                            </el-icon>登录app
                        </el-button>

                    </el-tag>

                    <el-button @click="pull_app(scope.row)" text type="primary" class="p-1">
                        <el-icon class="el-icon--left" :size="16">
                        </el-icon>拉取app
                    </el-button>
                    <el-button @click="push_app(scope.row)" text type="primary" class="p-1">
                        <el-icon class="el-icon--left" :size="16">
                        </el-icon>推送app
                    </el-button>
                </template>
            </el-table-column>

            <el-table-column prop="plate_account" label="账户号" width="100" style="text-align: center" align="center " />


            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row)" text type="primary" class="p-1">
                        <el-icon class="el-icon--left" :size="16">
                            <Edit />
                        </el-icon>修改
                    </el-button>
                    <el-popconfirm title="是否要删除该平台？" confirmButtonText="确认" cancelButtonText="取消"
                        @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button text type="danger" class="p-1">
                                <el-icon class="el-icon--left" :size="16">
                                    <Delete />
                                </el-icon>删除
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="pageSize" @current-change="getList" />
        </div>


        <!-- 新增/修改 -->
        <FormDrawer destroyOnClose ref="formDrawerRef" size="30%" :title="drawerTitle" @submit="selfHandleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="150px" :inline="false">
                <el-tabs type="border-card" @tab-change="onChangeTab">
                    <el-tab-pane label="个人用户" v-if="$store.state.user.type == '0'">
                        <el-form-item label="用户" prop="username">
                            <el-select placeholder="请选择用户" v-model="form.username" @change="changeUser"
                                style="width: 100%">
                                <el-option v-for="item in allUser" :key="item.id" :label="item.username"
                                    :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="平台" prop="en_name">
                            <el-select placeholder="请选择平台" v-model="form.en_name" @change="changePlatefrom"
                                style="width: 100%">
                                <el-option v-for="item in allPlatefrom" :key="item.id" :label="item.en_name"
                                    :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="账户号" prop="plate_account">
                            <el-input v-model="form.plate_account" placeholder="请填写账户手机号"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="企业用户" v-if="$store.state.user.type != '0'">

                        <!-- <el-form-item label="企业" prop="company_id">
                            <el-select placeholder="请选择所属企业..." v-model="form.company_name" @change="changeCompany"
                                style="width: 100%">
                                <el-option v-for="item in companyList" :key="item.id" :label="item.name"
                                    :value="item"></el-option>
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="平台" prop="en_name">
                            <el-select placeholder="请选择平台" v-model="form.en_name" @change="changePlatefrom"
                                style="width: 100%">
                                <el-option v-for="item in allPlatefrom" :key="item.id" :label="item.en_name"
                                    :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="账户号" prop="plate_account">
                            <el-input v-model="form.plate_account" placeholder="请填写账户手机号"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
                <!-- <el-form-item label="上传营业执照" >
            <UploadFile :data="{img_url:form.license_url,image_license_url:form.image_license_url}" @success="handleUploadSuccess" />
          </el-form-item> -->

            </el-form>
        </FormDrawer>



        <el-dialog v-model="dialogVisible" title="Tips" width="30%" :before-close="handleClose">
            <span>请填写手机号{{ phone }}收到的验证码</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-input v-model="code" placeholder="请输入验证码" clearable></el-input>
                    <el-button size="small" type="primary" @click="set_code(curr_id)">确定</el-button>
                </span>
            </template>

        </el-dialog>

    </el-card>

</template>
<script setup>
// vue 内部方法
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
// 页面组件
import ListHeader from "~/components/ListHeader.vue"
import FormDrawer from "~/components/FormDrawer.vue"
import SearchForm from "~/components/SearchForm.vue"
import SearchItem from "~/components/SearchItem.vue"
import UploadFile from "~/components/UploadFile.vue"
import { Search } from '@element-plus/icons-vue'
import { ElLoading } from 'element-plus'

// 公共方法
import { useInitTable, useInitForm } from "~/composables/useCommon"
import { toast } from "~/composables/util.js"

// api
import {
    getUserPlatefromList,
    postUserPlatefromList,
    putUserPlatefromList,
    deleteUserPlatefromList
} from "~/api/user/platefrom"

import {
    getPlatefromAll,
} from "~/api/platefrom/index"

import {
    getALLUserList,
    getUserLoginAppDirPhone,
    getUserAppFile,
    pushUserLoginAppDirPhone,
    getUserLoginAppDirCode,
} from "~/api/user/index"

import { getALLCompanyList } from '~/api/company/index'

const store = useStore()


// 初始化表格
const {
    searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    pageSize,
    getList,
    handleDelete,
} = useInitTable({
    searchForm: { search: "", id: "", username: "" },
    requestListAPI: getUserPlatefromList,
    delete: deleteUserPlatefromList,
    // pageSize: store.state.pageSize.MessageList,
    pageSize: 10,
    onGetListSuccess: (res) => {
        tableData.value = res.data.results
    },
})

// 初始化表单
const {
    formDrawerRef,
    formRef,
    form,
    rules,
    editId,
    drawerTitle,
    handleSubmit,
    resetForm,
    handleEdit,
} = useInitForm({
    getList,
    create: postUserPlatefromList,
    update: putUserPlatefromList,
    form: {
        user_id: "",
        user_name: "",
        platefrom_id: "",
        company_name: "",
        company_id: "",
        en_name: "",
        type: '0',
        plate_account: "",
        app_acccount_upload: "",
    },
    onGetDataSuccess: (res) => {
        // 将接口返回的公司列表数据命名为companyAllList
        //   companyAllList.value = res.data.name;
    },
    rules: {
        user_id: [
            {
                required: true,
                message: "用户不能为空",
                trigger: "blur",
            },
        ],
        plate_account: [
            {
                required: true,
                message: "平台账户不能为空",
                trigger: "blur",
            },
        ],
        platefrom_id: [
            {
                required: true,
                message: "平台不能为空",
                trigger: "blur",
            },
        ],
    }

});


// 修改 handleCreate 方法
const handleCreate = () => {
    formDrawerRef.value.open()
    resetForm()
    // 如果是个人用户，自动选择第一个用户
    if (store.state.user.type == '0' && allUser.value.length > 0) {
        const firstUser = allUser.value[0]
        form.user_id = firstUser.id
        form.username = firstUser.username
    }
}

// 加载用户和平台
const allUser = ref([])
const allPlatefrom = ref([])
const companyList = ref([])
onMounted(() => {
    // 用户
    getALLUserList().then((res) => {
        allUser.value = res.data
    })

    // 平台
    getPlatefromAll().then((res) => {
        allPlatefrom.value = res.data
    })

    // 企业
    // 获取公司用户
    getALLCompanyList().then((res) => {
        companyList.value = res.data
    })


})



// tab触发事件
const onChangeTab = (tabname) => {
    if (tabname == '0') {   // 个人用户
        form.company_name = ''
        form.company_id = ''
        form.type = 0
    } else {
        form.user_id = ''
        form.skus_id = ''
        form.type = 1
    }
}

// 提交
const selfHandleSubmit = () => {
    if (store.state.user.type == '0') {
        form.company_name = ''
        form.company_id = ''
        form.type = 0
    } else {
        form.company_name = companyList.value[0].name
        form.company_id = companyList.value[0].id
        form.type = 1
    }
    handleSubmit()
}

// 选择用户
const changeUser = (res) => {
    form.user_id = res.id
    form.username = res.username
    form.company_id = ''
    form.company_name = ''
}

// 选择公司
const changePlatefrom = (res) => {
    form.platefrom_id = res.id
    form.en_name = res.en_name
}


// 选择公司
const changeCompany = (res) => {
    form.company_id = res.id
    form.company_name = res.name
    form.user_id = ''
    form.username = ''
}

// 登录app获取账户登录文件
const dialogVisible = ref(false)
const code = ref('')
const phone = ref('')
const curr_id = ref('')
const fullscreenLoading = ref(false)
const login_app = (row) => {
    phone.value = row.plate_account
    curr_id.value = row.id
    fullscreenLoading.value = true
    getUserLoginAppDirPhone(row.id).then((res) => {
        if (res.code == 200) {
            toast('发送成功！')
            dialogVisible.value = true
            fullscreenLoading.value = false
        }
    })
}

// 推送账户到app上
const push_app = (row) => {
    phone.value = row.plate_account
    curr_id.value = row.id
    fullscreenLoading.value = true
    pushUserLoginAppDirPhone(row.id).then((res) => {
        if (res.code == 200) {
            fullscreenLoading.value = false
            toast('推送成功！')
        }
    })
}

// 拉取账户文件
const pull_app = (row) => {
    fullscreenLoading.value = true
    getUserAppFile(row.id).then((res) => {
        if (res.code == 200) {
            toast('拉取成功！')
            fullscreenLoading.value = false
            getList()
        }
    })
}




const set_code = (id) => {
    let data = {}
    data.id = id
    data.code = code.value
    getUserLoginAppDirCode(data).then((res) => {
        if (res.detail == '绑定成功') {
            dialogVisible.value = false
            phone.value = ''
            curr_id.value = ''
            code.value = ''
            toast('绑定成功!请点击拉取app！')
        }
    })
}


</script>

<style scoped></style>